package sskj.regulatory.data.repository

import android.os.Build.VERSION_CODES.M
import com.hikvision.sdk.net.bean.LoginData
import sskj.regulatory.data.response.session.TokenResponse
import io.reactivex.Flowable
import sskj.regulatory.data.cache.MemoryCache
import sskj.regulatory.data.mapper.Mapper
import sskj.regulatory.data.network.AuthApiService
import sskj.regulatory.data.network.UserApiService
import sskj.regulatory.data.pref.Preferences
import sskj.regulatory.data.request.JwtAuthenticationRequest
import sskj.regulatory.data.request.QrLoginRequest
import sskj.regulatory.data.response.session.IndexDataResponse
import sskj.regulatory.data.response.Response
import sskj.regulatory.data.response.eng.EngResponse
import sskj.regulatory.domain.entity.user.BingDingEntity
import sskj.regulatory.domain.entity.user.UserEntity
import sskj.regulatory.domain.fetcher.result_listener.RequestType
import sskj.regulatory.domain.repository.UserRepository

class UserDataRepository(
        private val authApiService: AuthApiService,
        private val userApiService: UserApiService,
        private var preferences: Preferences,
        private val memoryCache: MemoryCache,
        private val mapper: Mapper) : UserRepository {

    override fun saveAlong() {
        preferences.saveAlong()
    }

    //是否可以发送验证码
    override fun isSendVCode(): Boolean {
        return preferences.isSendVCode
    }

    //
    override fun updatePassword(userEntity: UserEntity): Flowable<Response> {
        return authApiService.updatePwd(userEntity)
    }

    override fun clearData(requestType: RequestType) {
        memoryCache clearCacheFor requestType
    }

    //解绑
    override fun delBingDing(id: String): Flowable<Response> {
        return userApiService.delBingDing(id).doOnNext { memoryCache.clearCacheFor(RequestType.INDEXDATA) }
    }

    //项目部扫码登录
    override fun xmbQrLogin(qrCode: String, username: String, password: String): Flowable<Response> {
        return userApiService.xmbQrLogin(QrLoginRequest("home.seam", qrCode, username, "", password))
    }

    //项目部扫码登录确定
    override fun xmbDoQrLogin(qrCode: String, loginIn: Boolean): Flowable<Response> {
        return userApiService.xmbDoQrLogin(QrLoginRequest("home.seam", qrCode, "", "", "", loginIn))
    }

    //绑定用户
    override fun bingDing(bidngDingEntity: BingDingEntity): Flowable<Response> {
        return userApiService.bingDing(bidngDingEntity).doOnNext { memoryCache.clearCacheFor(RequestType.INDEXDATA) }
    }

    //项目部认证
    override fun xmbAuth(username: String, password: String): Flowable<EngResponse> {
//        return authApiService.xmbAuth(JwtAuthenticationRequest(username, password))
        return if (memoryCache.hasCacheFor(RequestType.XMB_AUTH)) {
            Flowable.fromCallable<EngResponse> { memoryCache.getCacheForType(RequestType.XMB_AUTH) }
        } else {
            authApiService.xmbAuth(JwtAuthenticationRequest(username, password))
                    .doOnNext { memoryCache.put(RequestType.XMB_AUTH, it) }
        }
    }

    /**检查用户名是否已经注册
     *
     */
    override fun isRegister(username: String): Flowable<Response> {
        return authApiService.isRegister(username)
    }

    //刷新TOKEN
    override fun refreshToken(): Flowable<TokenResponse> {
        return userApiService.refresh()
    }

    /**注册用户
     *
     */
    override fun registerUser(userEntity: UserEntity): Flowable<Response> {
        return authApiService.register(userEntity)
    }

    /**发送注册 验证码短信
     *
     */
    override fun sendVCode(phone: String, vCode: String, signName: String,
                           templateCode: String, templateParam: String, outId: String): Flowable<Response> {
        return authApiService.sendVCode(phone, vCode, signName, templateCode, templateParam, outId)
    }

    /** 根据登录用户初始化用户数据
     *
     */
    override fun getIndexData(): Flowable<IndexDataResponse> {

        //如果缓存中有就从缓存中获取 如果没有就新增
        return if (memoryCache.hasCacheFor(RequestType.INDEXDATA)) {
            Flowable.fromCallable<IndexDataResponse> { memoryCache.getCacheForType(RequestType.INDEXDATA) }
        } else {
            userApiService.getIndexData()
                    .doOnNext { memoryCache.put(RequestType.INDEXDATA, it) }
        }
    }

    override fun getToken(username: String, password: String): Flowable<TokenResponse> =
            authApiService.getToken(JwtAuthenticationRequest(username, password))


    /**保存token
     *
     */
    override fun saveToken(token: String?) {
        preferences.saveUserToken(token)

    }

    override fun getUser(): Flowable<UserEntity> {
        return userApiService.getUser().map {
            mapper.translate(it)
        }
    }

    override fun logIn() {
        preferences.saveUserLoggedIn()
    }

    override fun clearLoginData() {
        preferences.saveUserLoggedOut()
        preferences.deleteToken()
    }

    override fun isUserLoggedIn() = preferences.isUserLoggedIn

    override fun clearCache() {
        memoryCache.clearCache()
    }
}